//
//  CreateEventMapViewController.m
//  jungoo
//
//  Created by Dang Quang Trung on 9/6/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "CreateEventMapViewController.h"
#import "MyAnnotation.h"
#import "JSON.h"
@implementation NSDictionary (Extension)

- (id)newObjectForKey:(id)aKey
{
    id rez = [self objectForKey:aKey];
    
    return ([rez isKindOfClass:[NSNull class]] ? nil : rez);
}
@end

@implementation CreateEventMapViewController

@synthesize mapView,data;

- (void)back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)done:(id)sender
{
    //http://maps.google.com/maps/geo?output=xml&q=0,0
    double latitude = locCoord.latitude;
    double longitude = locCoord.longitude;
    
    NSString *selectedLat = [NSString stringWithFormat:@"%f",latitude];
    [data setObject:selectedLat forKey:@"selectedLat"];
    
    NSString *selectedLon = [NSString stringWithFormat:@"%f",longitude];
    [data setObject:selectedLon forKey:@"selectedLon"];
    
    NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%f,%f&output=json", latitude, longitude];   
    NSURL *url = [NSURL URLWithString:urlString];
    
    
    NSString *locationString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
   // NSLog(@"%@",locationString);
    NSDictionary *dic = [locationString JSONValue];
     NSLog(@"%@",dic);
    NSArray *placemarkArr = [dic newObjectForKey:@"Placemark"] ;
    
    NSDictionary *addressDic = [placemarkArr objectAtIndex:0];
    NSString *address = [addressDic newObjectForKey:@"address"];
    NSLog(@"%@",address);
    [data setObject:@"" forKey:@"address"];
    [data setObject:address forKey:@"address"];
    [data setObject:[NSString stringWithFormat:@"%f",latitude] forKey:@"addressLat"];
    [data setObject:[NSString stringWithFormat:@"%f",longitude] forKey:@"addressLon"];
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)initTopBar
{
    [self setRightButtonImageActiveName:nil 
                           inactiveName:@"done-button" 
                                 target:self 
                                 action:@selector(done:)];
    
    [self setLeftButtonImageActiveName:nil 
                          inactiveName:@"back-button.png" 
                                target:self 
                                action:@selector(back:)];
    [self setTitle:@"Find on map"];
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bg"]];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
-(void) initMapView 
{
    mapView.showsUserLocation = YES;
    mapView.mapType=MKMapTypeStandard;	
    
    MKCoordinateRegion region;
    MKCoordinateSpan span;
    span.latitudeDelta = 0.01;
    span.longitudeDelta = 0.01;
    CLLocationCoordinate2D location;
    //NSString *lat = [JGoUtility sharedLatitude];
    //NSString *lon = [JGoUtility sharedLongitude];
    NSString *lat;
    NSString *lon;
    lat = [data newObjectForKey:@"selectedLat"];
    lon = [data newObjectForKey:@"selectedLon"];
    if (lat == nil || lon == nil || [lat isEqualToString:@""] || [lon isEqualToString:@""]) {
        lat = [JGoUtility sharedLatitude];
        lon = [JGoUtility sharedLongitude];
    }
    location.latitude = [lat doubleValue] ;
    location.longitude = [lon doubleValue];
    
    
    region.span = span;
    region.center = location;
    [mapView regionThatFits:region]; 
    [mapView setRegion:region animated:TRUE];
    MyAnnotation *anno = [[MyAnnotation alloc] initWithCoords:location name:@""];
    [mapView addAnnotation:anno];
    
    

}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initTopBar];
    [self initMapView];
    UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressGesture:)];
    [self.mapView addGestureRecognizer:longPressGesture];
    [longPressGesture release];
}

-(void)handleLongPressGesture:(UIGestureRecognizer*)sender 
{
    // This is important if you only want to receive one tap and hold event
    if (sender.state == UIGestureRecognizerStateEnded)
    {
        [self.mapView removeGestureRecognizer:sender];
    }
    else
    {
        // Here we get the CGPoint for the touch and convert it to latitude and longitude coordinates to display on the map
        CGPoint point = [sender locationInView:self.mapView];
         locCoord = [self.mapView convertPoint:point toCoordinateFromView:self.mapView];
        // Then all you have to do is create the annotation and add it to the map
        MyAnnotation *dropPin = [[MyAnnotation alloc] initWithCoords:locCoord name:@""];
        
        [self.mapView addAnnotation:dropPin];
        [dropPin release];
        

    }
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
